//
//  CLike.m
//  HCHK_iphone
//
//  Created by yilong zhang on 11-12-13.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "CLike.h"

@implementation CLike

@synthesize m_Product;

-(id)initWithProduct:(CProduct*)product
{
    self = [super init];
    if (self)
    {
        self.m_Product = product;
    }
    
    return self;
}

-(void)dealloc
{
    [m_Product release];

    [super dealloc];
}

-(int)SaveLike:(NSString*)tablename IconPath:(NSString*)iconPath ImagePath:(NSString*)imagepath
{
    int nRet = [self.m_Product SaveProductWithPathes:tablename IconPath:[NSString stringWithFormat:@"%@/%lld_icon.jpg", iconPath, [self.m_Product.P_AID longLongValue]] ImagePath:[NSString stringWithFormat:@"%@/%lld_image.jpg", imagepath, [self.m_Product.P_AID longLongValue]]];
    
    if (0 == nRet)
    {
        //NSLog(@"<====收藏成功====>");
        //save images
        [self SaveIcon:iconPath];
        [self SaveImage:imagepath];
    }
    else 
    {
        NSLog(@"<====收藏失败====>");
    }
    
    return nRet;
}

-(void)SaveIcon:(NSString*)rootpath
{
    NSString *path = [NSString stringWithFormat:@"%@/%lld_icon.jpg", rootpath, [self.m_Product.P_AID longLongValue]];
    if (![[NSFileManager defaultManager] copyItemAtPath:self.m_Product.P_Icon toPath:path error:nil])
    {
        NSLog(@"Save like's icon failed.");
    }
}

-(void)SaveImage:(NSString*)rootpath
{
    NSString *path = [NSString stringWithFormat:@"%@/%lld_image.jpg", rootpath, [self.m_Product.P_AID longLongValue]];
    if (![[NSFileManager defaultManager] copyItemAtPath:self.m_Product.P_Image toPath:path error:nil])
    {
        NSLog(@"Save like's image failed.");
    }
}

-(void)RemoveLike:(NSString*)tablename IconPath:(NSString*)iconPath ImagePath:(NSString*)imagepath
{
    int nRet = [CProduct RemoveProduct:tablename Where:[NSString stringWithFormat:@"P_AID==%ld", [self.m_Product.P_AID longValue]]];
    
    if (0 == nRet)
    {
        //remove images
        [self RemoveIcon:iconPath];
        [self RemoveImage:imagepath];
    }
    else 
    {
        NSLog(@"Cancel favorite failed.");
    }
}

-(void)RemoveIcon:(NSString*)rootpath
{
    NSString *path = [NSString stringWithFormat:@"%@/%ld_icon.jpg", rootpath, [self.m_Product.P_AID longValue]];
    if (![[NSFileManager defaultManager] removeItemAtPath:path error:nil])
    {
        NSLog(@"remove like's icon failed.");
    }
}

-(void)RemoveImage:(NSString*)rootpath
{
    NSString *path = [NSString stringWithFormat:@"%@/%ld_image.jpg", rootpath, [self.m_Product.P_AID longValue]];
    if (![[NSFileManager defaultManager] removeItemAtPath:path error:nil])
    {
        NSLog(@"remove like's image failed.");
    }
}

@end
